const fs = require('fs');
const { Console } = require('console');
const exec = require('child_process').exec;

const readCookieFromFile = () => {
    return new Promise((resolve, reject) => {
        fs.readFile('cookie.txt', 'utf-8', (err, data) => {
            if (err) {
                reject(err);
            } else {
                if (data.indexOf('Cookie:') === 0) {
                    data = data.substr(7).trim();
                }
                resolve(data);
            }
        });
    });
}
exports.readCookieFromFile = readCookieFromFile;

const syncExec = cmdStr => {
    return new Promise((resolve, reject) => {
        exec(cmdStr, (err, stdout, stderr) => {
            if (err) {
                return reject(err);
            } else {
                if (stderr) {
                    logger('stderr', stderr);
                }
                resolve(stdout);
            }
        });
    });
}
exports.syncExec = syncExec;

//console信息输出到文件
const output = fs.createWriteStream('./stdout.log');
const errOutput = fs.createWriteStream('./stderr.log');
const consoleLogger = new Console({stdout: output, stderr: errOutput});

const sleep = ms => {
	return new Promise(resolve => setTimeout(resolve, ms));
}
exports.sleep = sleep;

const logger = function() {
	console.log('[', (new Date()).Format("yyyy-MM-dd hh:mm:ss"), ']', ...arguments);
	consoleLogger.log('[', (new Date()).Format("yyyy-MM-dd hh:mm:ss"), ']', ...arguments);
	return null;
}
exports.logger = logger;

const httpGet = url => {
	return new Promise((resolve, reject) => {
		superagent.get(url).timeout(30000)
			.set('user-agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36')
			.end((err, res) => {
				if (err) {
					return reject(err);
				}
				resolve({
                    body: res.text,
                    setCookie: res.headers['set-cookie'],
                });
			});
	});
}
exports.httpGet = httpGet;

